package com.doit.day02;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;


public class Exercise {
    public static void main(String[] args) throws InterruptedException {

        Properties props = new Properties();
        //需要设置什么咱现在也不懂。。。
        //这三个参数是创建生产者必须得配置的
        props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "linux01:9092");

        //选配的  kafka生产者的应答机制
        props.setProperty(ProducerConfig.ACKS_CONFIG,"-1");
//        props.setProperty("log.message.timestamp.type","LogAppendTime");

        //创建一个生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);

        EventLog eventLog = new EventLog();

        //通过对象去调用api 发送数据
        //封装发送的数据，并且指定发到哪个topic中
        while (true){

            eventLog.setGuid(RandomUtils.nextInt(10000,1000000));
            eventLog.setEvent(RandomStringUtils.randomAlphabetic(10));
            eventLog.setTimestamp(System.currentTimeMillis());
            //将对象转换成json串
            String json = JSON.toJSONString(eventLog);
            //解析json串
            EventLog eventLog1 = JSON.parseObject(json, EventLog.class);
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("event",json);
            //发送数据
            producer.send(producerRecord);
            Thread.sleep(RandomUtils.nextInt(50,200));
            producer.flush();
        }




    }
}
